package edu.mit.csail.relo.ui;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.log4j.Logger;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;

import edu.mit.csail.relo.ReloPlugin;

public class FeedbackDialog extends Dialog {
	static final Logger s_logger = ReloPlugin.getLogger(FeedbackDialog.class);

    private Text nameEdit;
    private Text emailEdit;
    private Text commentsEdit;
    
    public static class FeedbackDlgAction extends ReloAction {
		@Override
		public void run(IAction action) {
        	FeedbackDialog dlg = new FeedbackDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
        	dlg.open();
		}
    }

    protected FeedbackDialog(Shell parentShell) {
		super(parentShell);
	}

    @Override
    protected void configureShell(Shell newShell) {
        super.configureShell(newShell);
        newShell.setText("Relo Feedback");
     }

    @Override
    protected Control createDialogArea(Composite parent) {
        Composite composite = (Composite) super.createDialogArea(parent);

        Label messageLabel = new Label(composite, SWT.WRAP);
        messageLabel.setText("Feedback (or bug reports) will help in focusing current and future efforts within Relo.");
        GridData data = new GridData(GridData.GRAB_HORIZONTAL
                | GridData.HORIZONTAL_ALIGN_FILL
                | GridData.VERTICAL_ALIGN_BEGINNING);
        data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
        messageLabel.setLayoutData(data);
        
        createBodyArea(composite);
        
        return composite;
     }

	private void createBodyArea(Composite parent) {
        Composite composite = new Composite(parent, SWT.NONE);
        GridData data = new GridData(GridData.GRAB_HORIZONTAL
                | GridData.HORIZONTAL_ALIGN_FILL
                | GridData.VERTICAL_ALIGN_BEGINNING);
        data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
        composite.setLayoutData(data);

        GridLayout layout = new GridLayout();
        layout.numColumns = 2;
        composite.setLayout(layout);

        Label lbl;

        lbl = new Label(composite, SWT.WRAP);
        lbl.setText("Name:\n(optional)");
        lbl.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
        
        nameEdit = new Text(composite, SWT.SINGLE | SWT.BORDER);
        nameEdit.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
        
        lbl = new Label(composite, SWT.WRAP);
        lbl.setText("E-mail address:\n(optional)");
        lbl.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
        
		emailEdit = new Text(composite, SWT.SINGLE | SWT.BORDER);
        emailEdit.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
        
        lbl = new Label(composite, SWT.WRAP);
        lbl.setText("Comments:");
        lbl.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
        
		commentsEdit = new Text(composite, SWT.MULTI | SWT.BORDER);
        commentsEdit.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 5));
        
		lbl = new Label(composite, SWT.WRAP);
        lbl.setText(" ");
        lbl.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));

        lbl = new Label(composite, SWT.WRAP);
        lbl.setText(" ");
        lbl.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
        
        lbl = new Label(composite, SWT.WRAP);
        lbl.setText(" ");
        lbl.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
        
        lbl = new Label(composite, SWT.WRAP);
        lbl.setText(" ");
        lbl.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
	}

    @Override
	protected void createButtonsForButtonBar(Composite parent) {
        createButton(parent, IDialogConstants.OK_ID, "Send Feedback", true);
        createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
    }

    @Override
	protected void buttonPressed(int buttonId) {
    	if (buttonId == IDialogConstants.CANCEL_ID) close();
    	
    	if (buttonId == IDialogConstants.OK_ID) {
    		this.getButton(IDialogConstants.OK_ID).setText("Sending...");
    		try {
				sendFeedback();
			} catch (IOException e) {
				s_logger.error("Error while sending feedback", e);
			}
    		close();
    	}
    }

	private void sendFeedback() throws IOException {
		System.err.println(this.nameEdit.getText());
		System.err.println(this.emailEdit.getText());
		System.err.println(this.commentsEdit.getText());

		URL url;
		URLConnection urlConn;

		// URL of CGI-Bin script.
		url = new URL("http://relo.csail.mit.edu/send-feedback.php");

		urlConn = url.openConnection();
		urlConn.setDoInput(true);
		urlConn.setUseCaches(false);
		urlConn.setDoOutput(true);

		urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

	    String content =
			"name=" + URLEncoder.encode (this.nameEdit.getText(), "UTF-8") +
			"&email=" + URLEncoder.encode (this.emailEdit.getText(), "UTF-8") +
			"&comments=" + URLEncoder.encode (this.commentsEdit.getText(), "UTF-8")	;

	    DataOutputStream printout = new DataOutputStream (urlConn.getOutputStream ());
	    printout.writeBytes (content);
	    printout.flush ();
	    printout.close ();

	    // Get response data (otherwise the connection is not happy).
		DataInputStream input;
	    input = new DataInputStream (urlConn.getInputStream ());
	    BufferedReader rdr = new BufferedReader(new InputStreamReader(input));
	    while (null != rdr.readLine()) {}
		//System.out.println (str);
	    rdr.close();
	    input.close ();
	    
	}
}
